<template>
	<div class="foSi14" style="padding: 20px;">
		<div class="foSi12 hei20" style="color: #787878;">基本信息</div>
		<el-form ref="ruleForm" :model="ruleForm" :rules="rules">
			<el-form-item label="班级名称" prop="name" class="hei44 dis disAl mar-bott15"
				style="background: #f2f2f2;padding: 0 20px;">
				<el-input v-model="ruleForm.name" style="width: 464px;" placeholder="请填写班级名称(1~15字)" />
			</el-form-item>
			<el-form-item label="封面" prop="imageUrl" class="dis disAl mar-bott15"
				style="background: #f2f2f2;padding: 10px 20px;">
				<div class="">
					<div calss="upImg bacFFF">
						<el-upload action="#" :http-request="handleAvatarSuccess" :before-upload="beforeAvatarUpload" :show-file-list="false" class="upImg1">
							<img v-if="ruleForm.imageUrl" :src="ruleForm.imageUrl" class="wh100">
							<div v-else class="bacFFF wh100"><span class="goods-img__add-inner">添加图片</span></div>
						</el-upload>
					</div>
					<div class="goods-imgs__tips mar-top10">建议尺寸:750*422像素，大小不超过5M</div>
				</div>
			</el-form-item>
			<el-form-item label="开课时间" prop="start" class="hei44 dis disAl mar-bott15"
				style="background: #f2f2f2;padding: 0 20px;">
				<el-date-picker v-model="ruleForm.start" value-format="yyyy-MM-dd HH:mm:ss" style="width: 200px;" type="date" placeholder="请选择开课时间" />
			</el-form-item>
			<el-form-item label="结课时间" prop="end" class="hei44 dis disAl mar-bott15"
				style="background: #f2f2f2;padding: 0 20px;">
				<el-date-picker v-model="ruleForm.end" value-format="yyyy-MM-dd HH:mm:ss" style="width: 200px;" type="date" placeholder="请选择结课时间" />
			</el-form-item>
			<el-form-item label="班级课时" prop="hour" class="hei44 dis disAl mar-bott15"
				style="background: #f2f2f2;padding: 0 20px;">
				<el-input v-model="ruleForm.hour" style="width: 464px;" placeholder="请输入班级课时数量" />
			</el-form-item>
			<el-form-item label="课程描述" class="hei44 dis disAl mar-bott15" style="background: #f2f2f2;padding: 0 20px;">
				<el-input v-model="ruleForm.text" style="width: 464px;" maxlength="20" placeholder="描述一下班课的亮点，限20字" />
			</el-form-item>
<!--			<el-form-item label="购买人限制" class="hei44 dis disAl mar-bott15" style="background: #f2f2f2;padding: 0 20px;">-->
<!--				<el-checkbox-group v-model="ruleForm.check">-->
<!--					<el-checkbox :label="1">会员</el-checkbox>-->
<!--					<el-checkbox :label="2">访客</el-checkbox>-->
<!--				</el-checkbox-group>-->
<!--			</el-form-item>-->
			<el-form-item label="售价" prop="sellingPrice" class="hei44 dis disAl mar-bott20"
				style="background: #f2f2f2;padding: 0 20px;">
				<div class="dis disAl">
					<div class="dis disAl cuPo" @click.stop="ruleForm.sellingPrice = 0">
						<div class="dis disAl disJuC bacFFF borRad50"
							style="width: 14px;height: 14px;border: 1px solid #41c3a8;">
							<div v-if="ruleForm.sellingPrice === 0" class="borRad50"
								style="width: 6px;height: 6px;background: #41c3a8;" />
						</div>
						<div class="mar-left5">免费</div>
					</div>
					<div class="dis disAl cuPo mar-left30" @click.stop="ruleForm.sellingPrice = 1">
						<div class="dis disAl disJuC bacFFF borRad50"
							style="width: 14px;height: 14px;border: 1px solid #41c3a8;">
							<div v-if="ruleForm.sellingPrice === 1" class="borRad50"
								style="width: 6px;height: 6px;background: #41c3a8;" />
						</div>
						<div class="dis disAl mar-left5">
							<span>收费</span>
							<el-form-item prop="charge" class="mp0">
								<el-input v-model="ruleForm.charge" class="mar-left10 mar-right10" style="width: 70px;"
									:disabled="ruleForm.sellingPrice !== 1" />
							</el-form-item>
							<span>元</span>
						</div>
					</div>
				</div>
			</el-form-item>
			<el-form-item v-if="ruleForm.sellingPrice === 1" label="优惠价" class="hei44 dis disAl mar-bott20"
				style="background: #f2f2f2;padding: 0 20px;">
				<div class="dis disAl">
					<div class="dis disAl cuPo" @click.stop="ruleForm.discounts = 0">
						<div class="dis disAl disJuC bacFFF borRad50"
							style="width: 14px;height: 14px;border: 1px solid #41c3a8;">
							<div v-if="ruleForm.discounts === 0" class="borRad50"
								style="width: 6px;height: 6px;background: #41c3a8;" />
						</div>
						<div class="mar-left5">无优惠</div>
					</div>
					<div class="dis disAl cuPo mar-left30" @click.stop="ruleForm.discounts = 1">
						<div class="dis disAl disJuC bacFFF borRad50"
							style="width: 14px;height: 14px;border: 1px solid #41c3a8;">
							<div v-if="ruleForm.discounts === 1" class="borRad50"
								style="width: 6px;height: 6px;background: #41c3a8;" />
						</div>
						<div class="dis disAl mar-left5">
							<span>优惠</span>
							<el-form-item prop="discountsCharge" class="mp0">
								<el-input v-model="ruleForm.discountsCharge" class="mar-left10 mar-right10"
									style="width: 70px;" :disabled="ruleForm.discounts !== 1" />
							</el-form-item>
							<span>元</span>
						</div>
					</div>
				</div>
			</el-form-item>
			<el-form-item v-if="ruleForm.sellingPrice === 1" label="优惠时间" class="hei44 dis disAl mar-bott20"
				style="background: #f2f2f2;padding: 0 20px;">
				<div class="dis disAl">
					<el-form-item prop="startCharge" class="mp0">
						<el-date-picker v-model="ruleForm.startCharge" style="width: 200px;" type="date"
							placeholder="请选择优惠时间" value-format="yyyy-MM-dd HH:mm:ss" :picker-options="pickerOptions" />
					</el-form-item>
					<div class="mar-left15 mar-right15">至</div>
					<el-form-item prop="endCharge" class="mp0">
						<el-date-picker v-model="ruleForm.endCharge" style="width: 200px;" type="date"
							placeholder="请选择优惠时间" value-format="yyyy-MM-dd HH:mm:ss" :picker-options="pickerOptions" />
					</el-form-item>
				</div>
			</el-form-item>
			<el-form-item label="人数上限" prop="upperLimit" class="hei44 dis disAl mar-bott20"
				style="background: #f2f2f2;padding: 0 20px;">
				<div class="dis disAl">
					<div class="dis disAl cuPo" @click.stop="ruleForm.upperLimit = 1">
						<div class="dis disAl disJuC bacFFF borRad50"
							style="width: 14px;height: 14px;border: 1px solid #41c3a8;">
							<div v-if="ruleForm.upperLimit === 1" class="borRad50"
								style="width: 6px;height: 6px;background: #41c3a8;" />
						</div>
						<div class="mar-left5">不限</div>
					</div>
					<div class="dis disAl cuPo mar-left30" @click.stop="ruleForm.upperLimit = 2">
						<div class="dis disAl disJuC bacFFF borRad50"
							style="width: 14px;height: 14px;border: 1px solid #41c3a8;">
							<div v-if="ruleForm.upperLimit === 2" class="borRad50"
								style="width: 6px;height: 6px;background: #41c3a8;" />
						</div>
						<div class="dis disAl mar-left5">
							<span>限制</span>
							<el-form-item prop="astrict" class="mp0">
								<el-input v-model="ruleForm.astrict" class="mar-left10 mar-right10" style="width: 70px;"
									:disabled="ruleForm.upperLimit !== 2" />
							</el-form-item>
							<span>人</span>
						</div>
					</div>
				</div>
			</el-form-item>
			<el-form-item label="请假" prop="leave" class="hei44 dis disAl mar-bott20"
				style="background: #f2f2f2;padding: 0 20px;">
				<div class="dis disAl">
					<div class="dis disAl cuPo" @click.stop="ruleForm.leave = 0">
						<div class="dis disAl disJuC bacFFF borRad50"
							style="width: 14px;height: 14px;border: 1px solid #41c3a8;">
							<div v-if="ruleForm.leave === 0" class="borRad50"
								style="width: 6px;height: 6px;background: #41c3a8;" />
						</div>
						<div class="mar-left5">不允许</div>
					</div>
					<div class="dis disAl cuPo mar-left30" @click.stop="ruleForm.leave = 1">
						<div class="dis disAl disJuC bacFFF borRad50"
							style="width: 14px;height: 14px;border: 1px solid #41c3a8;">
							<div v-if="ruleForm.leave === 1" class="borRad50"
								style="width: 6px;height: 6px;background: #41c3a8;" />
						</div>
						<div class="dis disAl mar-left5">
							<span>允许</span>
							<el-form-item prop="allow" class="mp0">
								<el-input v-model="ruleForm.allow" class="mar-left10 mar-right10" style="width: 70px;"
									:disabled="ruleForm.leave !== 1" />
							</el-form-item>
							<span>次</span>
							<span class="mar-left10" style="color: #ff1f1f;">（如允许请假，请假期间不扣除课时）</span>
						</div>
					</div>
				</div>
			</el-form-item>
			<el-form-item label="班级简介" class="dis" style="background: #f2f2f2;padding: 20px;">
				<div class="class-desc">
					<el-upload action="#" :http-request="handleAvatarSuccess1" :before-upload="beforeAvatarUpload">
						<div class="rich-insert">
							<svg-icon icon-class="up-editior" class="mar0 cuPo" style="width: 25px;height: 25px;" />
							<span class="mar-left10">插入图片</span>
						</div>
					</el-upload>
					<div class="rich-row" contenteditable="true" @click="handleSelection" @input="handleSelection" />
				</div>
			</el-form-item>

		</el-form>

		<div class="wid100 dis disAl disJuC foSi14 coFFF" style="padding: 40px 0;">
			<div class="mar-right20 que cuPo" style="background: #48a9f3;" @click.stop="submitForm('ruleForm')">保存</div>
			<div class="que cuPo" style="background: #616b74;" @click.stop="fanhui">取消</div>
		</div>
	</div>
</template>

<script>
	import { uploadimg } from '@/api/utils';
  import {
    getClassAddEdit
  } from '@/api/class';
  export default {
		name: 'ClassPrivateAdd',
		components: {},
		data() {
			const validateHour = (rule, value, callback) => {
				if (!(/(^[1-9]\d*$)/.test(value))) {
					callback(new Error('班级课时（正整数）'))
				} else {
					callback()
				}
			}
			const validateCharge = (rule, value, callback) => {
				var reg = new RegExp('^-?[0-9]*.?[0-9]*$')
				if (this.ruleForm.sellingPrice === 2) {
					if (!reg.test(value) || !value || value === 0) {
						callback(new Error('请填写数值(0.01~1000000)'))
					} else {
						var absVal = Math.abs(value)
						if (Number(value) !== absVal || value > 1000000) {
							callback(new Error('请填写数值(0.01~1000000)'))
						} else {
							callback()
						}
					}
				} else {
					callback()
				}
			}
			const validateDiscounts = (rule, value, callback) => {
				var reg = new RegExp('^-?[0-9]*.?[0-9]*$')
				if (this.ruleForm.discounts === 2) {
					if (!reg.test(value) || !value || value === 0) {
						callback(new Error('请填写数值(0.01~1000000)'))
					} else {
						var absVal = Math.abs(value)
						if (Number(value) !== absVal || value > 1000000) {
							callback(new Error('请填写数值(0.01~1000000)'))
						} else {
							callback()
						}
					}
				} else {
					callback()
				}
			}
			const validateAstrict = (rule, value, callback) => {
				var reg = new RegExp('^-?[0-9]*.?[0-9]*$')
				if (this.ruleForm.upperLimit === 2) {
					if (!reg.test(value) || !value || value === 0) {
						callback(new Error('请填写数值(1~10000)'))
					} else {
						var absVal = Math.abs(value)
						if (Number(value) !== absVal || value > 10000) {
							callback(new Error('请填写数值(1~10000)'))
						} else {
							callback()
						}
					}
				} else {
					callback()
				}
			}
			const validateAllow = (rule, value, callback) => {
				var reg = new RegExp('^-?[0-9]*.?[0-9]*$')
				if (this.ruleForm.leave === 1) {
					if (!reg.test(value) || !value || value === 0) {
						callback(new Error('请填写数值(1~10000)'))
					} else {
						var absVal = Math.abs(value)
						if (Number(value) !== absVal || value > 100) {
							callback(new Error('请填写数值(1~100)'))
						} else {
							callback()
						}
					}
				} else {
					callback()
				}
			}
			return {
				pickerOptions: {
					disabledDate(time) {
						return time.getTime() < Date.now() - 8.64e7
					}
				},
				selection: null,
				range: null,
				textNode: null,
				rangeStartOffset: null,
				imageUrl: '',
				ruleForm: {
					name: '',
					imageUrl: '',
					start: '',
					end: '',
					hour: '',
					text: '',
					// check: [1, 2],
					sellingPrice: 0,
					charge: '',
					discounts: 0,
					discountsCharge: '',
					startCharge: '',
					endCharge: '',
					upperLimit: 1,
					astrict: '',
					leave: 0,
					allow: '',
          class_introduction:''
				},
				rules: {
					name: [{
						required: true,
						message: '请填写班级名称(1~15字)',
						trigger: 'blur'
					}],
					imageUrl: [{
						required: true,
						message: '请上传封面',
						trigger: 'change'
					}],
					start: [{
						required: true,
						message: '请选择时间',
						trigger: 'change'
					}],
					end: [{
						required: true,
						message: '请选择时间',
						trigger: 'change'
					}],
					hour: [{
						required: true,
						trigger: 'blur',
						validator: validateHour
					}],
					sellingPrice: [{
						required: true,
						trigger: 'change',
						message: '请选择'
					}],
					charge: [{
						required: true,
						trigger: 'blur',
						validator: validateCharge
					}],
					discountsCharge: [{
						required: true,
						trigger: 'blur',
						validator: validateDiscounts
					}],
					upperLimit: [{
						required: true,
						trigger: 'change',
						message: '请选择'
					}],
					astrict: [{
						required: true,
						trigger: 'blur',
						validator: validateAstrict
					}],
					leave: [{
						required: true,
						trigger: 'change',
						message: '请选择'
					}],
					allow: [{
						required: true,
						trigger: 'blur',
						validator: validateAllow
					}],
					startCharge: [{
						required: true,
						message: '请选择时间',
						trigger: 'change'
					}],
					endCharge: [{
						required: true,
						message: '请选择时间',
						trigger: 'change'
					}]
				}
			}
		},
		created() {
			this.$store.dispatch('user/changeXuan', {
				key: 'xuanList',
				value: [{
					name: '新增班级',
					url: '/course/classPrivateAdd',
					pd: true
				}]
			})
			this.$store.dispatch('user/changeXuan', {
				key: 'xuan',
				value: 0
			})
			this.getList()
		},
		methods: {
			fanhui() {
				this.$router.push({
					path: '/course/classPrivateList'
				})
			},
			handleTag() {
				const parseDom = this.parseDom(`<img src="${this.imageUrl}">`)
				// 在光标处插入dom
				this.range.insertNode(parseDom)
				// 光标开始和光标结束重叠
				this.range.collapse(true)
			},
			// 记录光标位置等 （debounce防抖提升性能）
			handleSelection(e) {
				this.selection = getSelection()
				// 光标对象
				this.range = this.selection.getRangeAt(0)
				// 获取光标对象的范围界定对象
				this.textNode = this.range.startContainer
				// 获取光标位置
				this.rangeStartOffset = this.range.startOffset
				console.log(e.target.innerHTML)
        this.ruleForm.class_introduction = e.target.innerHTML
			},
			// 转dom对象
			parseDom(arg) {
				var objE = document.createElement('div')
				objE.innerHTML = arg
				return objE.childNodes[0]
			},
      handleAvatarSuccess(file) {
        var that = this
        const mf = new FormData()
        mf.append('file', file.file)
        uploadimg(mf).then(response => {
          this.ruleForm.imageUrl = response.data
          that.handleTag()
        })
      },
      handleAvatarSuccess1(file) {
        var that = this
        const mf = new FormData()
        mf.append('file', file.file)
        uploadimg(mf).then(response => {
          that.imageUrl = response.data
          that.handleTag()
        })
      },
			beforeAvatarUpload(file) {
				const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
				const isLt2M = file.size / 1024 / 1024 < 5
				if (!isJPG) {
					this.$message.error('上传头像图片只能是 JPG或PNG 格式!')
				}
				if (!isLt2M) {
					this.$message.error('上传头像图片大小不能超过 5MB!')
				}
				return isJPG && isLt2M
			},
			submitForm(formName) {
				this.$refs.ruleForm.validate((valid) => {
					if (valid) {
						// this.fanhui()
            console.log(this.ruleForm);
            var params = {
              'name':this.ruleForm.name,
              'cover':this.ruleForm.imageUrl,
              'start_time':this.ruleForm.start,
              'end_time':this.ruleForm.end,
              'class_hours':this.ruleForm.hour,
              'class_des':this.ruleForm.text,
              'pay_type':this.ruleForm.sellingPrice,
              'money':this.ruleForm.charge,
              'discount':this.ruleForm.discounts,
              'discount_start_time':this.ruleForm.startCharge,
              'discount_end_time':this.ruleForm.endCharge,
              'max_people':this.ruleForm.astrict,
              'leaves':this.ruleForm.leave,
              'class_introduction':this.ruleForm.class_introduction
            };

            getClassAddEdit(params).then(response => {
              const {
                data
              } = response
              console.log(data)
              this.fanhui()
            }).catch(error => {
              console.log(error)
            })
					} else {
						this.$message.error('请按规则填写完整信息')
						return false
					}
				})
			},
			getList() {}
		}
	}
</script>

<style lang="scss" scoped>
	::v-deep .el-form-item__label {
		width: 140px;
		text-align: left;
	}

	.que {
		display: inline-block;
		padding: 0 24px;
		height: 34px;
		line-height: 34px;
		text-align: center;
		vertical-align: top;
	}

	.upImg {
		width: 148px;
		height: 84px;
		overflow: hidden;
	}

	.goods-img__add-inner {
		display: inline-block;
		padding-left: 20px;
		background: url('../../icons/png/icon-add-s.png') no-repeat left 3px center;
	}

	.upImg1 ::v-deep .el-upload {
		width: 148px;
		height: 84px;
		line-height: 84px;
		border: 1px solid #d9d9d9;
		color: #41c3a8 !important;
		font-size: 12px;
	}

	.goods-imgs__tips {
		color: #b8b8b8;
		line-height: 1;
	}

	::v-deep .el-checkbox__input.is-checked .el-checkbox__inner {
		background-color: #41c3a8;
		border-color: #41c3a8;
	}

	::v-deep .el-checkbox__input.is-focus .el-checkbox__inner {
		border-color: #41c3a8;
	}

	::v-deep .el-checkbox__label {
		color: #000 !important;
	}

	.class-desc {
		width: 900px;
		height: 360px;
		border: 1px solid #d9d9d9;
		padding: 5px;
		line-height: 1.5;
	}

	.rich-insert {
		width: 100%;
		height: 30px;
		padding: 2px 5px;
		position: relative;
		vertical-align: text-top;
		box-sizing: border-box;
		overflow: hidden;
		display: flex;
		align-items: center;
	}

	.rich-row {
		width: 100%;
		height: calc(100% - 31px);
		border: 0;
		background-color: #fff;
		box-sizing: border-box;
		padding: 5px;
		margin-top: 1px;
		outline: 0;
		overflow-y: scroll;
		overflow-x: hidden;
	}

	::v-deep .el-upload:focus {
		color: #000 !important;
	}

	::v-deep .el-upload-list {
		display: none;
	}
</style>
